package com.dunqi.gpm.cangxi.home.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.util.CommonUtil;
import com.dunqi.gpm.cangxi.common.view.ComTitleBar;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;


public class Video2Activity extends AppCompatActivity {

    private static final String NAME = "name";
    private VideoView videoView;
    private TextView percentTv;
    private TextView netSpeedTv;
    private int mVideoLayout = 0;

    private static final String MAINURL = "mainUrl";
    private static final String SONURL = "sonUrl";
    private String mainUrl;
    private String sonUrl;
    private String title;
    private ComTitleBar titleBar;
    String videoUrl;
    private View stateView;
    private View progressBar;
    private View backIv;
    private View changeStreamTv;
    private TextView steamTv;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_video2);


        initUiAndListener();
    }

    protected void initUiAndListener() {
        Intent intent = getIntent();
        if (intent != null) {
            mainUrl = intent.getStringExtra(MAINURL);
            sonUrl = intent.getStringExtra(SONURL);
            title = intent.getStringExtra(NAME);
        }
        videoUrl = sonUrl;

        //显示缓冲百分比的TextView
        percentTv = (TextView) findViewById(R.id.buffer_percent);
        //显示下载网速的TextView
        netSpeedTv = (TextView) findViewById(R.id.net_speed);
        //初始化加载库文件

        progressBar = findViewById(R.id.progress_bar);

        stateView = findViewById(R.id.state_view);

        backIv = findViewById(R.id.back_iv2);
        changeStreamTv = findViewById(R.id.change_stream_tv);

        steamTv = findViewById(R.id.stream_tv);

        steamTv.setText("当前是子码流");

        initStateView();


        init();

        titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle(title);


        changeStreamTv.setOnClickListener(new ChangeSteamListener());
        titleBar.setOnClickListenerOfRight(new ChangeSteamListener());

        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    class ChangeSteamListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            isMainUrl = !isMainUrl;

            if (isMainUrl) {
                CommonUtil.showSingleToast("当前是主码流");
                steamTv.setText("当前是主码流");
                videoUrl = mainUrl;
            } else {
                CommonUtil.showSingleToast("当前是子码流");
                steamTv.setText("当前是子码流");
                videoUrl = sonUrl;
            }
            videoView.stopPlayback();
            clearVideo();
            if (TextUtils.isEmpty(videoUrl)) {
                CommonUtil.showSingleToast("播放地址为空，请尝试切换码流");
                return;
            }
            videoView.setVideoURI(Uri.parse(videoUrl));
//            videoView.start();
        }
    }

    private void clearVideo() {

        videoView.getHolder().addCallback(new SurfaceHolder.Callback2() {
            @Override
            public void surfaceRedrawNeeded(SurfaceHolder holder) {


            }

            @Override
            public void surfaceCreated(final SurfaceHolder holder) {
                new Thread() {
                    @Override
                    public void run() {
                        if (holder != null) {
                            Canvas canvas = holder.lockCanvas();
                            if (canvas != null) {
                                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                                holder.unlockCanvasAndPost(canvas);
                            }
                        }
                    }
                }.start();

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }


    private void initStateView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            stateView.setVisibility(View.VISIBLE);
        } else {
            stateView.setVisibility(View.GONE);
        }
    }

    private void init() {
        if (Vitamio.isInitialized(this)) {
            videoView = (VideoView) findViewById(R.id.vitamio);
            if (TextUtils.isEmpty(videoUrl)) {
                CommonUtil.showSingleToast("播放地址为空，请尝试切换码流");
            }else {
                videoView.setVideoURI(Uri.parse(videoUrl));
            }
            videoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);

            final MediaController controller = new MediaController(this);
            videoView.setMediaController(controller);
            videoView.setBufferSize(10240); //设置视频缓冲大小。默认1024KB，单位byte
            videoView.requestFocus();
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    // optional need Vitamio 4.0
                    mediaPlayer.setPlaybackSpeed(1.0f);
                    //mediaPlayer.setLooping(true);
                }
            });

            videoView.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    percentTv.setText("已缓冲：" + percent + "%");
                }
            });

            videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(MediaPlayer mp, int what, int extra) {
                    switch (what) {
                        //开始缓冲
                        case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                            progressBar.setVisibility(View.VISIBLE);
                            percentTv.setVisibility(View.VISIBLE);
                            netSpeedTv.setVisibility(View.VISIBLE);
                            mp.pause();
                            break;
                        //缓冲结束
                        case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                            progressBar.setVisibility(View.GONE);
                            percentTv.setVisibility(View.GONE);
                            netSpeedTv.setVisibility(View.GONE);
                            mp.start(); //缓冲结束再播放
                            break;
                        //正在缓冲
                        case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:
                            netSpeedTv.setText("当前网速:" + extra + "kb/s");
                            break;
                    }
                    return true;
                }
            });
            controller.setOnFullClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    } else {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    }
                }
            });

        }
    }

    boolean isMainUrl = false;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // land donothing is ok
            stateView.setVisibility(View.GONE);
            titleBar.setVisibility(View.GONE);
            backIv.setVisibility(View.VISIBLE);
            changeStreamTv.setVisibility(View.VISIBLE);

        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // port donothing is ok  竖屏
            titleBar.setVisibility(View.VISIBLE);
            backIv.setVisibility(View.GONE);
            changeStreamTv.setVisibility(View.GONE);
            initStateView();
        }

    }

//    @Override
//    public void onBackPressed() {
//        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        } else {
//            super.onBackPressed();
//        }
//
//    }


    public static void start(Context context, String mainUrl, String sonUrl, String title) {
        Intent intent = new Intent(context, Video2Activity.class);
        intent.putExtra(MAINURL, mainUrl);
        intent.putExtra(SONURL, sonUrl);
        intent.putExtra(NAME, title);
        context.startActivity(intent);

    }
}